<?php
/**
 * 活动表
 * User: cxm
 * Date: 2020/9/23
 * Time: 17:20
 */
namespace App\Http\Controllers\Admin\Activity;
use App\Http\Controllers\Admin\Controller;
use App\Models\Activity;
use App\Models\ActivityExtend;
use App\Models\AwardGoods;
use App\Models\AwardGoodsClass;
use App\Models\AwardHistory;
use App\Models\Region;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Validator,Excel;
use Illuminate\Http\Request;

class ActivityController extends Controller {
    /**
     * 活动列表
     * URL POST:admin/activity/getLists
     * @param Request $request
     * @param string keyword 活动名称
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['keyword','page','limit']);
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            $params['where'][] = ['name','like','%'.$keyword.'%'];
        }
        $params['orderBy'] = ['sort asc','created_at desc'];
        // 图片
        $params['with'][] = 'file:id,path';
        $data = Activity::listByWhere($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 获取所有活动
     * URL POST:/admin/activity/getAll
     * @param Request $request
     * @return mixed
     */
    public function getAll(Request $request){
        $params['orderBy'] = ['sort asc','created_at desc'];
        $data = Activity::getAll($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 活动添加、编辑处理
     * URL POST:/admin/activity/store
     * @param Request $request
     * @param int id 活动ID 编辑时必传
     * @param string share_title 分享标题
     * @param string name 活动名称
     * @param string describe 活动介绍
     * @param int goods_num 商品个数
     * @param string rules 抽奖规则
     * @param string start_time 活动开始时间
     * @param string end_time 活动结束时间
     * @param int image 图片
     * @param string get_time 奖品领取截止时间
     * @param int sort 排序
     * @return mixed
     */
    public function store(Request $request){
        $params = $request->only(['id','image','name','share_title','describe','rules','goods_num','start_time','end_time','sort','get_time']);
        $params['goods_num'] = isset($params['goods_num']) ? $params['goods_num'] : 1;
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'share_title'       => ['required'],
            'name'              => ['required'],
            //'image'             => ['required'],
            'start_time'        => ['required'],
            'goods_num'         => ['required'],
            'end_time'          => ['required'],
           // 'get_time'          => ['required'],
        ],[
            'share_title.required' => '分享标题是必须的',
            'name.required'     => '活动名称是必须的',
            //'image.required'    => '请上传图片',
            'goods_num.required' => '商品数量是必须的',
            'start_time.required'=> '活动开始时间是必须的',
            'end_time.required' => '活动结束时间是必须的',
            //'get_time.required' => '奖品领取截止时间是必须的'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $activity = new Activity();
        }else{
            $activity = Activity::find($id);
            if (!$activity) {
                return $this->error('活动不存在');
            }
        }
        $activity->share_title           = $params['share_title'];
        $activity->name                  = $params['name'];
        $activity->image                 = isset($params['image']) ? $params['image'] : '';
        $activity->goods_num             = $params['goods_num'];
        $activity->start_time            = isset($params['start_time']) ? $params['start_time'] : '';
        $activity->end_time              = isset($params['end_time']) ? $params['end_time'] : '';
        $activity->describe              = $params['describe'];
        $activity->rules                 = isset($params['rules']) ? $params['rules'] : '';
        $activity->get_time              = isset($params['get_time']) ? $params['get_time'] : '';
        $activity->sort                  = $params['sort'];
        $result = $activity->save();
        if (!$result) {
            return $this->error('操作失败');
        }
        // 创建辅助表
        if(!ActivityExtend::where('activity_id',$activity->id)->first()) {
            ActivityExtend::insert([
                'activity_id'       => $activity->id,
                'created_at'        => Carbon::now()
            ]);
        }
        return $this->success('操作成功');
    }

    /**
     * 删除
     * URL POST:/admin/activity/delete
     * @param Request $request
     * @param array ids 活动ID
     * @return mixed
     */
    public function delete(Request $request){
        $params =$request->only(['ids']);
        if (!array_key_exists('ids',$params) ||empty($params['ids'])) {
            return $this->error('请选择要删除的活动');
        }
        $result = Activity::whereIn('id',$params['ids'])->delete();
        if ($result === false) {
            return  $this->error('删除失败');
        }
        // 删除用户领取的情况
        $history = AwardHistory::whereIn('activity_id',$params['ids'])->delete();
        if ($history === false) {
            return  $this->error('删除用户领取记录失败');
        }
        return $this->success('删除成功');
    }

    /**
     * 修改排序
     * URL POST:/admin/activity/updateSort
     * @param Request $request
     * @param int id
     * @param int sort 排序值
     * @return mixed
     */
    public function updateSort(Request $request){
        $params =$request->only(['id','sort']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少ID');
        }
        $sort = isset($params['sort']) ? $params['sort'] : 1;
        $detail = Activity::find($params['id']);
        if (!$detail) {
            return $this->error('活动不存在');
        }
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['sort'=>$sort];
        $result = Activity::modify($where,$field);
        if ($result === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 是否显示
     * URL POST:/admin/activity/updateStatus
     * @param Request $request
     * @param int id 活动ID
     * @return mixed
     */
    public function updateStatus(Request $request){
        $params = $request->only(['id']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少活动ID');
        }
        $trader = Activity::find($params['id']);
        if (!$trader) {
            return $this->error('活动不存在');
        }
        $status = $trader->status == 1 ? 2 : 1;
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['status'=>$status];
        $res = Activity::modify($where,$field);
        if ($res === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 中奖列表
     * URL POST:/admin/activity/historyList
     * @param Request $request
     * @param int activity_id 活动ID
     * @param int status 状态 1已兑奖 2未兑奖
     * @param int type 搜索类型 1中奖用户名称2 奖品名称
     * @param string start_time 中奖开始时间
     * @Param string end_time 中奖结束时间
     * @return mixed
     */
    public function historyList(Request $request){
        $params = $request->only(['activity_id','type','start_time','end_time','page','limit','status','keyword']);
        $activity_id = isset($params['activity_id'])? $params['activity_id']:0;
        if ($activity_id > 0) {
            $params['where'][] = ['activity_id',$activity_id];
        }
        // 是否兑奖
        $status = isset($params['status']) ? $params['status'] : 0;
        if ($status > 0) {
            $params['where'][] = ['status',$status];
        }
        $type = isset($params['type']) ? $params['type'] : 1;
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            switch ($type){
                case 1:// 中奖用户名称
                    $params['whereHas'][] = ['user',function($query)use($keyword){
                        $query->where('mobile','like','%'.$keyword.'%')
                            ->orWhere('name','like','%'.$keyword.'%');
                    }];
                    break;
                case 2:// 奖品名称
                    $params['whereHas'][] = ['goods',function($query)use($keyword){
                        $query->where('name','like','%'.$keyword.'%');
                    }];
                    break;
            }
        }
        // 获奖的起止时间查询
        $start_time = isset($params['start_time']) ? $params['start_time'] : '';
        if (!empty($start_time)) {
            $params['where'][] = ['created_at','>=',$start_time];
        }
        $end_time = isset($params['end_time']) ? $params['end_time'] : '';
        if (!empty($end_time)) {
            $params['where'][] = ['end_time','<=',$end_time];
        }
        // 中奖用户
        $params['with'][] = 'user:id,mobile,name';
        // 奖品
        $params['with'][] = 'goods:id,name';
        $params['with'][] = ['goods'=>function($query){
            $query->select('id','name')
                ->with('goods');
         }];
        // 活动
        $params['with'][] = 'activity:id,name';
        $data = AwardHistory::listByWhere($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 兑奖
     * URL POST:/admin/activity/historyPrize
     * @param Request $request
     * @param int history_id 中奖记录ID
     * @return mixed
     */
    public function historyPrize(Request $request){
        $params = $request->only(['history_id']);
        if (!array_key_exists('history_id',$params) || empty($params['history_id'])) {
            return $this->error('缺少参数ID');
        }
        $trader = AwardHistory::find($params['history_id']);
        if (!$trader) {
            return $this->error('中奖记录不存在');
        }
        if ($trader->status == 1) {
            return $this->error('已领取');
        }
        $where = [];
        $where[] = ['id',$params['history_id']];
        $field = ['status'=>1];
        $res = AwardHistory::modify($where,$field);
        if ($res === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 添加、编辑用户领奖信息
     * URL POST:/admin/activity/userDrawInfo
     * @param Request $request
     * @param int history_id 中奖记录ID
     * @param int type 1、地址信息 2、手机
     * @param int goods_class_id 奖品ID
     * @param string award_name 奖品名称---奖品下面有选择分类的情况填写
     * @param string mobile 手机
     * @param string username 联系人
     * @param string province 省
     * @param string city 市
     * @param string district 区
     * @param string address 详细地址
     * @return mixed
     */
    public function userDrawInfo(Request $request){
        $params = $request->only(['history_id','type','goods_class_id','mobile','username','province','city','district','address','award_name']);
        $type = isset($params['type']) ? $params['type'] : 1;
        $validator = \Illuminate\Support\Facades\Validator::make($params,[
            'history_id'            => ['required'],
            'mobile'                => ['required','regex:/^1[3456789]\d{9}$/'],
            'username'              => [$type==1?'required':'nullable'],
            //'province'              => [$type==1?'required':'nullable'],
            //'city'                  => [$type==1?'required':'nullable'],
            //'district'              => [$type==1?'required':'nullable'],
            'address'               => [$type==1?'required':'nullable']
        ],[
            'history_id.required'   => '中奖记录ID是必须的',
            'mobile.required'       => '手机是必须的',
            'mobile.regex'          => '手机格式是必须的',
            'username.required'     => '用户名是必须的',
            //'province.required'     => '请选择省',
            //'city.required'         => '请选择市',
           // 'district.required'     => '请选择区',
            'address.required'      => '请输入详细地址'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        // 查看中奖信息是否存在
        $history = AwardHistory::find($params['history_id']);
        if (!$history) {
            return $this->error('中奖信息不存在');
        }
        // 地址信息
        if ($type == 1) {
            $data = [
                'mobile'        => $params['mobile'],
                'award_name'    => isset($params['award_name']) ? $params['award_name'] : '',
                'username'      => $params['username'],
                //'province'      => $params['province'],
                //'province_str'  => Region::getByIdName($params['province']),
                //'city'          => $params['city'],
                //'city_str'      => Region::getByIdName($params['city']),
                //'district'      => $params['district'],
                //'district_str'  => Region::getByIdName($params['district']),
                'address'       => $params['address']
            ];
        }else{
            $data = [
                'mobile'    => $params['mobile']
            ];
        }
        $where = [];
        $where[] = ['id',$params['history_id']];
        $filed = [
            'draw_data'=>json_encode($data),
            'award_name'    => isset($params['award_name']) ? $params['award_name'] : '',
            'mobile'   => $params['mobile'],
            'username' => $params['username'],
            //'province' => $params['province'],
           // 'city'     => $params['city'],
            //'district' => $params['district'],
            'address'  => $params['address']
        ];
        $result = AwardHistory::modify($where,$filed);
        if ($result === false) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 抽奖用户导出
     * URL ANY:/admin/activity/historyExport
     * @param Request $request
     * @param int activity_id 活动ID
     * @param int status 状态 1已兑奖 2未兑奖
     * @param int type 搜索类型 1中奖用户名称2 奖品名称
     * @param string start_time 中奖开始时间
     * @Param string end_time 中奖结束时间
     * @return mixed
     */
    public function historyExport(Request $request){
        $params = $request->only(['activity_id','type','start_time','end_time','page','limit','status','keyword','data']);
        $params = json_decode($params['data'],true);
        // 设置内存
        ini_set('memory_limit','1000M');
        //设置超时限制为0分钟(无限制, 默认30s)
        set_time_limit(0);
        $activity_id = isset($params['activity_id'])? $params['activity_id']:0;
        if ($activity_id > 0) {
            $params['where'][] = ['activity_id',$activity_id];
        }
        // 是否兑奖
        $status = isset($params['status']) ? $params['status'] : 0;
        if ($status > 0) {
            $params['where'][] = ['status',$status];
        }
        $type = isset($params['type']) ? $params['type'] : 1;
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            switch ($type){
                case 1:// 中奖用户名称
                    $params['whereHas'][] = ['user',function($query)use($keyword){
                        $query->where('mobile','like','%'.$keyword.'%')
                            ->orWhere('name','like','%'.$keyword.'%');
                    }];
                    break;
                case 2:// 奖品名称
                    $params['whereHas'][] = ['goods',function($query)use($keyword){
                        $query->where('name','like','%'.$keyword.'%');
                    }];
                    break;
            }
        }
        // 获奖的起止时间查询
        $start_time = isset($params['start_time']) ? $params['start_time'] : '';
        if (!empty($start_time)) {
            $params['where'][] = ['created_at','>=',$start_time];
        }
        $end_time = isset($params['end_time']) ? $params['end_time'] : '';
        if (!empty($end_time)) {
            $params['where'][] = ['end_time','<=',$end_time];
        }
        // 中奖用户
        $params['with'][] = 'user:id,mobile,name,card_no';
        // 奖品
        $params['with'][] = 'goods:id,name';
        $params['with'][] = ['goods'=>function($query){
            $query->select('id','name')
                ->with('goods');
        }];
        // 活动
        $params['with'][] = 'activity:id,name';
        $data = AwardHistory::getAll($params);
        return Excel::download(new \App\Excel\HistoryExport($data), time().'_中奖信息导出.xlsx');
    }
}